package com.starlinkdt.common.utils.Encrypt;

import com.starlinkdt.common.annotation.DecryptField;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.sql.Statement;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Properties;

/**
 * @author zhourenbao
 * @version 1.0
 * @description: TODO
 * @date 2025/6/26 09:52
 */
@Slf4j
@Component
@Intercepts({@Signature(
        type = ResultSetHandler.class,
        method = "handleResultSets",
        args = {Statement.class}
)})
public class DecryptInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();
        if (result instanceof List<?>) {
            for (Object obj : (List<?>) result) {
                Class<?> currentClass = obj.getClass();
                while (currentClass != null && currentClass != Object.class) {
                    Field[] fields = currentClass.getDeclaredFields();
                    for (Field field : fields) {
                        if (field.isAnnotationPresent(DecryptField.class)) {
                            field.setAccessible(true);
                            String value = (String) field.get(obj);
                            if (value != null && !value.isEmpty()) {
                                try {
                                    String decrypted = EncryptUtils.decrypt(value);
                                    field.set(obj, decrypted);
                                } catch (Exception e) {
                                    log.error("【解密失败】" + value, e);
                                }
                            }
                        }
                    }
                    currentClass = currentClass.getSuperclass();
                }
            }
        }
        return result;
    }


    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {}
}